package com.heima.controller.web;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Slf4j
@RestController
@RequestMapping("/static")
public class StaticController {


    @Value("${lkd_parent1.path}")
    private String basePath;

    @Autowired
    HttpServletResponse response;

    @Autowired
    HttpServletRequest request;

    //下载
    @GetMapping("/{name}")
    public void download(@PathVariable String name) throws IOException {
//        String myfile = (String) request.getSession().getAttribute("myfile");
        //1. 定义输入流，关联拼接后的对应文件。如果图片文件不存在，就直接结束请求
//        String substring = name.substring(8);
        System.out.println(name);

        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(new File(basePath, name)));
        } catch (FileNotFoundException e) {
            log.warn("图片文件找不到");
            return;
        }
//        2. 通过`response`对象，获取到输出流
        ServletOutputStream os = null;
        try {
            os = response.getOutputStream();
        } catch (IOException e) {
            log.warn("响应图片失败");
            e.printStackTrace();
        }

        //3. 通过`response`对象设置响应数据格式(`image/jpeg`)
//        response.setContentType("application/json");
        response.setContentType("image/jpeg");

        //4. 通过输入流读取文件数据，然后通过上述的输出流写回浏览器
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = bis.read(bytes)) > 0) {
            os.write(bytes, 0, len);
            os.flush();
        }
        //5. 关闭资源
        bis.close();
    }
}
